package com.charges.util;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.http.*;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;
 
import java.util.Map;


/**
 * 通用HTTP请求工具类
 */
@Slf4j
public class RestTemplateUtils {
 
 
    /**
     * 通用HTTP请求方法
     *
     * @param requestBody 请求体内容
     * @param url 完整请求url
     * @param httpMethod 请求方法类型 (GET, POST, PUT, DELETE等)
     * @return 响应内容字符串，失败时返回null
     */
    public static String executeRequest(Map<String, String> requestBody, String url, HttpMethod httpMethod) {
        RestTemplate restTemplate = new RestTemplate();
        try {
            // 请求头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            // 请求体
            HttpEntity<Map<String, String>> requestEntity = new HttpEntity<>(requestBody, headers);
            // 服务端地址、请求方法、请求实体（包含头和体、响应类型
            ResponseEntity<String> response = restTemplate.exchange(
                    url, httpMethod, requestEntity, String.class);
 
            if (!response.getStatusCode().is2xxSuccessful()) {
                throw new RuntimeException("HTTP请求失败，状态码: " + response.getStatusCode());
            }
            return response.getBody();
        } catch (Exception e) {
            log.error("HTTP请求失败: {} {}, 错误: {}", httpMethod, url, e.getMessage());
            return null;
        }
    }
 
 
 
    /**
     * 通用HTTP请求方法（支持任意请求体类型）
     *
     * @param requestBody 请求体内容，可以是Map、POJO或任何可序列化为JSON的对象
     * @param url         完整的请求URL（包含协议、主机、路径和参数）
     * @param httpMethod  请求方法类型（GET/POST/PUT/DELETE等）
     * @return 响应内容的字符串形式
     * @throws RuntimeException 当HTTP请求失败或返回非2xx状态码时抛出
     */
    public static String executeRequest(Object requestBody, String url, HttpMethod httpMethod) {
        RestTemplate restTemplate = new RestTemplate();
        try {
            // 请求头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            // 请求体
            HttpEntity<Object>  requestEntity = new HttpEntity<>(requestBody, headers);
 
            // 服务端地址、请求方法、请求实体（包含头和体、响应类型
            ResponseEntity<String> response = restTemplate.exchange(
                    url, httpMethod, requestEntity, String.class);
 
            if (!response.getStatusCode().is2xxSuccessful()) {
                throw new RuntimeException("HTTP请求失败，状态码: " + response.getStatusCode());
            }
            return response.getBody();
        } catch (Exception e) {
            log.error("HTTP请求失败: {} {}, 错误: {}", httpMethod, url, e.getMessage());
            return null;
        }
    }
 
 
 
    /**
     * 文件上传专用方法 (multipart/form-data)
     *
     * @param file       上传的文件
     * @param formData   其他表单字段
     * @param url        目标URL
     * @return 响应内容
     */
    public static String uploadFile(MultipartFile file, Map<String, String> formData, String url, String fileName) {
        RestTemplate restTemplate = new RestTemplate();
        try {
            // 1. 构建 MultipartBody
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.MULTIPART_FORM_DATA);  // 关键！
            if (StringUtils.isNotEmpty(fileName)) {
                headers.set("accept", "application/json");  // 添加 accept 头
            }
 
            MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
            // 设置文件名
            fileName = StringUtils.isEmpty(fileName)? "file": fileName;
            // 添加文件
            body.add(fileName, new ByteArrayResource(file.getBytes()) {
                @Override
                public String getFilename() {
                    return file.getOriginalFilename();  // 保留原始文件名
                }
            });
            // 添加其他表单字段（如果有）
            if (formData != null) {
                formData.forEach(body::add);
            }
 
            // 2. 发送请求
            HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(body, headers);
            ResponseEntity<String> response = restTemplate.postForEntity(url, requestEntity, String.class);
 
            if (!response.getStatusCode().is2xxSuccessful()) {
                throw new RuntimeException("上传失败，状态码: " + response.getStatusCode());
            }
            return response.getBody();
        } catch (Exception e) {
            log.error("文件上传失败: {}, 错误: {}", url, e.getMessage());
            return null;
        }
    }
}